package com.lzx.iteam;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.util.Log;
import com.lzx.iteam.adapter.TreeViewAdapter;
import com.lzx.iteam.bean.ElementData;
import com.lzx.iteam.util.DateUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;


import com.lzx.iteam.bean.ChatContact;
import com.lzx.iteam.bean.CloudContact;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetStructureMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.widget.PullListView;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class TreeFrag extends Fragment implements AdapterView.OnItemClickListener, OnItemLongClickListener {

    private final int MSG_GROUP_STRUCTURE = 1000;
    public ArrayList<ElementData> topElements;

    /**
     * 树中的元素集合
     */
    private ArrayList<ElementData> elements;
    /**
     * 数据源元素集合
     */
    private ArrayList<ElementData> elementsData;

    ElementData root;

    private /*ListView*/ PullListView treeview;
    private RelativeLayout mRlNotice;

    private String mGid;
    private String mGroupName;
    private String mContactId;
    public int mCount;
    private int mGroupType;//是否允许成员添加新人(16或18 都是允许添加新人;2：非允许)
    private TreeViewAdapter treeViewAdapter;
    private LayoutInflater inflater;
    public int currentPosition = -1;
    public String mCreateType;//-1:虚拟成员(对于号码簿模板来说); 0:未注册成员;1:普通成员;2:管理者;3:创建者
    public boolean isBatch = false;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_GROUP_STRUCTURE:
                    if (msg.arg1 == 0) {
                        elements = new ArrayList<ElementData>();
                        elementsData = new ArrayList<ElementData>();
                        Map<String, ArrayList<ElementData>> map = (Map<String, ArrayList<ElementData>>) msg.obj;
                        topElements = map.get("top");
                        elements = new ArrayList<ElementData>();
                        for (ElementData it : topElements) {
                            elements.add(it);
                        }
                        elementsData = map.get("all");
//                        if (treeViewAdapter != null){
//                            treeViewAdapter.cleanWait();
//                        }
//                        cleanWait();
                        if (elementsData.size() > 0) {
                            treeViewAdapter = new TreeViewAdapter(
                                  inflater, (TreeFrag.this), Integer.parseInt(mGid), mGroupName, isBatch, mCount, mContactId);
                            treeViewAdapter.root = root;
                            treeViewAdapter.selectId = -1;
                            treeViewAdapter.initData(elements, elementsData);
                            treeview.setAdapter(treeViewAdapter);
                            treeview.setSelection(currentPosition);
                            getAllContact();
                            treeview.onRefreshComplete("最近更新：" + DateUtil.getUpDateTime(System.currentTimeMillis()));
                        }

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText((TreeFrag.this.getActivity()), R.string.active_failure_no_network,
                                  Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText((TreeFrag.this.getActivity()), (String) msg.obj,
                                  Toast.LENGTH_LONG).show();

                        }
                    }
                    break;

                default:
                    break;
            }
        }
    };


    public static TreeFrag newInstance(Bundle args) {
        TreeFrag f = new TreeFrag();
        f.setArguments(args);
        return f;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getData();

    }

    private void getData() {

        Bundle bundle = this.getArguments();
        mGid = bundle.getString("group_id");
        mCount = bundle.getInt("contact_count", 0);
        mGroupName = bundle.getString("group_name");
        mGroupType = bundle.getInt("group_type", 0);
        mCreateType = bundle.getString("user_type","1");
        mContactId = bundle.getString("contact_id");

        root = new ElementData();//CloudDialerActivity.instance.chooseelement;
        root.setContentText("全部成员");
        if (CloudDialerActivity.instance.rootcontactList != null) {
            root.setContactCount(CloudDialerActivity.instance.rootcontactList.size());
        } else {
            root.setContactCount(mCount);
        }
        root.id = -1;
        root.isExpanded = true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tree, container, false);

        mRlNotice = (RelativeLayout) v.findViewById(R.id.bottom_text);
        treeview = (PullListView) v.findViewById(R.id.lv_group_treeview);

        this.inflater = (LayoutInflater) this.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (isBatch == false) {
            if (mCreateType.equals("2") || mCreateType.equals("3")) {
                mRlNotice.setVisibility(View.VISIBLE);
                treeview.setOnItemLongClickListener(this);
            } else {
                mRlNotice.setVisibility(View.GONE);
            }
        } else {
            mRlNotice.setVisibility(View.GONE);
        }

        //treeViewAdapter.selectId = ((ElementData) treeViewAdapter.getItem(position)).getId();
        treeview.setOnItemClickListener(this);
        treeview.setType(1);
        treeview.setonRefreshListener(new PullListView.OnRefreshListener() {
            @Override
            public void onRefresh(boolean isTop) {

                getGroupStructure(mHandler.obtainMessage(MSG_GROUP_STRUCTURE));
                //treeview.onRefreshComplete("最近更新:");
            }
        });
        SharedPreferences sp = (this.getActivity()).getSharedPreferences("structure", Context.MODE_PRIVATE);
        String structureJson = sp.getString(mGid, "");
        Boolean flag = sp.getBoolean(mGid + "tag", false);
        if (flag == true) {
            elementsData = new ArrayList<ElementData>();
            elements = new ArrayList<ElementData>();
            if (!structureJson.isEmpty()) {
                Map<String, ArrayList<ElementData>> map = GetStructureMsg.getElementMsg(structureJson);
                topElements = map.get("top");
                elementsData = map.get("all");
                elements.addAll(topElements);
            } else {
                topElements = new ArrayList<ElementData>();
            }

            treeViewAdapter = new TreeViewAdapter(
                  inflater, TreeFrag.this, Integer.parseInt(mGid), mGroupName, isBatch, mCount, mContactId);
            treeViewAdapter.selectId = -1;
            treeViewAdapter.root = root;
            treeViewAdapter.initData(elements, elementsData);
            treeview.setSelection(currentPosition);
            treeview.setAdapter(treeViewAdapter);
            getAllContact();
        } else {
            getGroupStructure(mHandler.obtainMessage(MSG_GROUP_STRUCTURE));

        }

        return v;
    }


    public void addContactNum(int addnum) {
        this.mCount += addnum;
        root.contactCount += addnum;
        treeViewAdapter.notifyDataSetChanged();
    }

    /**
     * 设置父节点人数
     * @param parentid 父节点id
     * @param lists
     */
    void setParentNum(int parentid, ArrayList<ChatContact> lists) {
        Log.d("setParentNum","parentid="+parentid+",size="+lists.size());
        for (ElementData item : treeViewAdapter.elements) {
            if (item.id == parentid) {
                int addnum = 0;
                for (ChatContact cc : lists) {
                    boolean find = false;
                    if (item.contactList != null) {
                        for (CloudContact contact : item.contactList) {
                            if (contact.contactId.equals(cc.contactId)) {
                                find = true;
                                break;
                            }
                        }
                    }
                    if (find == false) {
                        addnum++;
                    }
                }
                if (item.contactList != null) {
                    item.setContactCount(item.contactList.size() + addnum);
                }
                item.contactList = null;

                if (item.parendId != 0) {//如果还有父节点，则接着设置
                    setParentNum(item.parendId, lists);
                }

                break;

            }
        }


    }


    //设置部门成员时调用，将成员数目更改
    public void setContactNum(ArrayList<ChatContact> lists) {
        ElementData element;
        if (this.currentPosition != -1){
            element = (ElementData) treeViewAdapter.getItem(this.currentPosition);
        }else {
            element = treeViewAdapter.root;
        }
        element.setContactCount(lists.size());//设置当前节点的人数

        if (element.parendId != 0) {
            setParentNum(element.parendId, lists);//设置父节点人数
        }

        treeViewAdapter.notifyDataSetChanged();

    }


    //View oldView;
    public void clearContactList() {
        int position = currentPosition;
        if (position >= 0) {
            ElementData element = (ElementData) treeViewAdapter.getItem(position);
            element.contactList = null;
        }

    }


    public void updateCurrentItem() {
        int position = currentPosition;
        if (treeViewAdapter == null || currentPosition == -1) {
            getAllContact();
            return;
        }

        String tagId = ((ElementData) treeViewAdapter.getItem(position)).getId() + "";
        String tagName = ((ElementData) treeViewAdapter.getItem(position)).getContentText();
        String tagCount = ((ElementData) treeViewAdapter.getItem(position)).getContactCount() + "";

        Intent intent = new Intent();
        intent.putExtra(Constants.INTENT_TAG_ID, tagId);
        intent.putExtra(Constants.INTENT_TAG_NAME, tagName);
        intent.putExtra("tag_count", tagCount);
        intent.putExtra("group_id", mGid);
        intent.putExtra("group_name", mGroupName);
        intent.putExtra("contact_count", mCount);
        intent.setAction("structure_tag_click");
        CloudDialerActivity.instance.chooseelement = (ElementData) treeViewAdapter.getItem(position);

        if (isBatch == false) {
            CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK, (ElementData) treeViewAdapter.getItem(position));
        } else {
            CloudDialerActivity.instance.ListRefresh(intent, -2, (ElementData) treeViewAdapter.getItem(position));
        }

    }

    void getAllContact() {
        if (CloudDialerActivity.mBatchOperationType != 0) {
            isBatch = true;
        } else {
            isBatch = false;
        }

        if (StringUtil.isEmpty(mGid)) {
            getData();
        }
        Intent intent = new Intent();
        intent.putExtra(Constants.INTENT_TAG_ID, "0");
        intent.putExtra(Constants.INTENT_TAG_NAME, "全部成员");
        intent.putExtra("tag_count", "");
        intent.putExtra("group_id", mGid);
        intent.putExtra("group_name", mGroupName);
        intent.putExtra("user_type", mCreateType);
        // intent.putExtra("contact_count", mCount);
        intent.setAction("structure_tag_click");
        CloudDialerActivity.instance.chooseelement = root;
        if (isBatch == false) {
            CloudDialerActivity.instance.ListRefresh(intent,
                  Activity.RESULT_OK, root);
        } else {
            CloudDialerActivity.instance.ListRefresh(intent, -2, root);
        }

    }


    private void getGroupStructure(Message callback) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_IS_ALL, "1"));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STRUCTURE_PID, "0"));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TYPE, mCreateType));
        GetStructureMsg getGroup = new GetStructureMsg(callback, this.getActivity(), this.mGid);
        getGroup.mApi = AsynHttpClient.API_TAGS_GET;
        getGroup.mParams = nvps;
        AsynHttpClient.getInstance(this.getActivity()).execCcHttp(getGroup);
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        if (position == 1) {//点击全部成员部分
            //treeViewAdapter.selectId = -1;
            TreeFrag.this.currentPosition = -1;
            getAllContact();

            if (root.isExpanded == true) {
                if (treeViewAdapter.selectId == -1) {//将所有的组织结构收回
                    treeViewAdapter.initData(new ArrayList<ElementData>(), new ArrayList<ElementData>());
                    root.isExpanded = false;
                }

            } else {//将组织结构第一级节点展示出来，节点处于非展开状态
                elements.clear();
                for (ElementData it : topElements) {
                    it.isExpanded = false;
                    elements.add(it);
                }

                treeViewAdapter.initData(elements, elementsData);
                root.isExpanded = true;
            }

            treeViewAdapter.selectId = -1;
            treeViewAdapter.notifyDataSetChanged();

            return;
        }

        // 点击节点
        position--;

        TreeFrag.this.currentPosition = position;

        String tagId = ((ElementData) treeViewAdapter.getItem(position)).getId() + "";
        String tagName = ((ElementData) treeViewAdapter.getItem(position)).getContentText();
        String tagCount = ((ElementData) treeViewAdapter.getItem(position)).getContactCount() + "";

        Intent intent = new Intent();
        intent.putExtra(Constants.INTENT_TAG_ID, tagId);
        intent.putExtra(Constants.INTENT_TAG_NAME, tagName);
        intent.putExtra("tag_count", tagCount);
        intent.putExtra("group_id", mGid);
        intent.putExtra("group_name", mGroupName);
        //intent.putExtra("contact_count", mCount);
        CloudDialerActivity.instance.tagId = tagId;
        CloudDialerActivity.instance.chooseelement = (ElementData) treeViewAdapter.getItem(position);

        intent.setAction("structure_tag_click");
        if (isBatch == false) {
            CloudDialerActivity.instance.ListRefresh(intent, Activity.RESULT_OK, (ElementData) treeViewAdapter.getItem(position));
        } else {
            CloudDialerActivity.instance.ListRefresh(intent, -2, (ElementData) treeViewAdapter.getItem(position));
        }

        treeViewAdapter.setTreeStyle(position);
        treeViewAdapter.selectId = ((ElementData) treeViewAdapter.getItem(position)).getId();

        view.setBackgroundResource(R.color.group_item_pressed);

        treeViewAdapter.notifyDataSetChanged();

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
        if (position == 1) {
            return false;
        }

        position--;
        TreeFrag.this.currentPosition = position;
        treeViewAdapter.currentPosition = currentPosition;
        CloudDialerActivity.instance.chooseelement = (ElementData) treeViewAdapter.getItem(position);
        treeViewAdapter.selectId = ((ElementData) treeViewAdapter.getItem(position)).getId();
        treeViewAdapter.mName = ((ElementData) treeViewAdapter.getItem(position)).getContentText();
        treeViewAdapter.mId = ((ElementData) treeViewAdapter.getItem(position)).getId();
        treeViewAdapter.mParentId = ((ElementData) treeViewAdapter.getItem(position)).getParendId();
        //treeViewAdapter.mTagPath = ((ElementData) treeViewAdapter.getItem(position)).getPath();
        treeViewAdapter.mContactCount = ((ElementData) treeViewAdapter.getItem(position)).getContactCount() + "";
        String tagName = ((ElementData) treeViewAdapter.getItem(position)).getContentText();
        treeViewAdapter.showButtonWindow(tagName, false, position);

        return false;
    }
}
